from django.contrib import admin
from django.contrib.auth.models import Group, Permission
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
from django.utils.html import format_html
from .models import PermissionCategory, SystemConfig


@admin.register(PermissionCategory)
class PermissionCategoryAdmin(admin.ModelAdmin):
    """权限分组管理"""
    list_display = (
        'name', 'get_full_name', 'parent', 'sort_order', 'created_at'
    )
    list_filter = ('parent', 'created_at')
    search_fields = ('name', 'description')
    ordering = ('sort_order', 'name')
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'parent')
        }),
        ('排序设置', {
            'fields': ('sort_order',)
        }),
    )

    def get_full_name(self, obj):
        """获取完整分组名称"""
        return obj.get_full_name()
    get_full_name.short_description = '完整路径'


class GroupAdmin(BaseGroupAdmin):
    """自定义用户组管理"""
    list_display = ('name', 'get_permissions_count', 'get_users_count')
    search_fields = ('name',)
    filter_horizontal = ('permissions',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name',)
        }),
        ('权限设置', {
            'fields': ('permissions',),
            'description': '选择该用户组拥有的权限'
        }),
    )

    def get_permissions_count(self, obj):
        """获取权限数量"""
        count = obj.permissions.count()
        return format_html(
            '<span style="color: {}">{} 个权限</span>',
            '#28a745' if count > 0 else '#6c757d',
            count
        )
    get_permissions_count.short_description = '权限数量'

    def get_users_count(self, obj):
        """获取用户数量"""
        count = obj.user_set.count()
        return format_html(
            '<span style="color: {}">{} 个用户</span>',
            '#007bff' if count > 0 else '#6c757d',
            count
        )
    get_users_count.short_description = '用户数量'


class PermissionAdmin(admin.ModelAdmin):
    """权限管理"""
    list_display = ('name', 'content_type', 'codename')
    list_filter = ('content_type',)
    search_fields = ('name', 'codename')
    ordering = ('content_type', 'codename')
    
    def has_add_permission(self, request):
        """禁止添加权限"""
        return False
    
    def has_delete_permission(self, request, obj=None):
        """禁止删除权限"""
        return False


@admin.register(SystemConfig)
class SystemConfigAdmin(admin.ModelAdmin):
    """系统配置管理"""
    list_display = (
        'key', 'get_value_preview', 'config_type', 
        'get_description_preview', 'updated_at'
    )
    list_filter = ('config_type', 'created_at', 'updated_at')
    search_fields = ('key', 'description')
    readonly_fields = ('created_at', 'updated_at')
    ordering = ('key',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('key', 'value', 'config_type')
        }),
        ('说明信息', {
            'fields': ('description',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def get_value_preview(self, obj):
        """获取配置值预览"""
        if obj.value:
            preview = str(obj.value)[:50]
            if len(str(obj.value)) > 50:
                preview += '...'
            return preview
        return '(空)'
    get_value_preview.short_description = '配置值'

    def get_description_preview(self, obj):
        """获取描述预览"""
        if obj.description:
            preview = obj.description[:30]
            if len(obj.description) > 30:
                preview += '...'
            return preview
        return '(无描述)'
    get_description_preview.short_description = '描述'


# 重新注册Group和Permission模型
admin.site.unregister(Group)
admin.site.register(Group, GroupAdmin)
admin.site.register(Permission, PermissionAdmin)

# 自定义Admin站点信息
admin.site.site_header = 'Django-Jazzmin权限管理系统'
admin.site.site_title = '权限管理系统'
admin.site.index_title = '欢迎使用权限管理系统'